package com.jdpc.weparty.service.udr

import com.jdpc.weparty.entity.Role
import com.jdpc.weparty.entity.Udr
import com.jdpc.weparty.entity.User
import com.jdpc.weparty.repository.UdrRepository
import com.jdpc.weparty.service.role.RoleService
import com.jdpc.weparty.service.user.UserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class UdrServiceImpl : UdrService {
    @Autowired
    lateinit var udrRepository: UdrRepository

    @Autowired
    lateinit var userService: UserService

    @Autowired
    lateinit var roleService: RoleService
//    @Autowired
//    lateinit var userRepository: UserRepository

    override fun getUsers(role: Role): Set<User> =
            udrRepository.findByRole(role)?.map {
                it.user ?: User()
            }?.toHashSet() ?: HashSet()


    override fun getRoles(userId: Int): Set<Role> =
            udrRepository.findByUserId(userId)?.map {
                it.role!!
            }?.toHashSet() ?: HashSet()

    override fun save(user: User, level: Int): Udr {
        val udr = Udr()
        udr.role = roleService.getRole(level)
        udr.user = user
        return udrRepository.save(udr)
    }

    override fun save(udr: Udr): Udr =
            udrRepository.save(udr)


    override fun saveAll(udr: List<Udr>): List<Udr> =
            udrRepository.saveAll(udr)


    override fun delete(id: Int) {
        udrRepository.deleteById(id)
    }

    override fun deleteAll(type: Role.RoleType) {
        val udrs = udrRepository.findByRole(roleService.getRole(type))
        udrs?.let {
            udrRepository.deleteAll(it)
        }
    }

    override fun update(udr: Udr) {
        udrRepository.save(udr)
    }

}